package com.runjian.rundo.iot.agent.common.entity;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.annotation.JSONField;

import lombok.Getter;
import lombok.Setter;

/**
 * 设备控制指令对象，数据来自DeviceInstanceControlVO，这里没有直接使用DeviceInstanceControlVO，而是转化了一层， 对多个服务的，拆分成单个服务对象
 *
 * @author LiGang
 */
@Getter
@Setter
public class CommonDeviceCommand {

    private static final  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    private String traceId;

    private String deviceId;



    // 默认等于10秒
    private Long timeOut = 10L;

    /**
     * 控制时间
     */
    @JSONField(name="time",format = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",deserialize = false)
    private ZonedDateTime time;

    /**
     * 控制时间
     */
    @JSONField(name="time",serialize = false)
    private String timeString;

    /**
     * 控制指标项键值对，key为series，value为测量值
     */
    private Map<String, Object> commands;

    /**
     * 已执行控制反馈的指标项
     */
    @JSONField(deserialize = false, serialize = false)
    private List<String> callbackSeries;

    public ZonedDateTime getTime() {
        if(time == null && StrUtil.isNotBlank(timeString)){
            time = ZonedDateTime.parse(timeString, formatter.withZone(ZoneId.of("Z")));
        }else if (time == null ) {
            time = LocalDateTime.now().atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC"));
        }
        return time;
    }
//
//    @JSONField(name="time",serialize = false)
//    public void setTime(String time) {
//        if (time == null) {
//            time = LocalDateTime.parse(time, "yyyy-MM-ddTHH:mm:ss.SSSZ").atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC"));
//        }
//        return time;
//    }

    public List<String> getCallbackSeries() {
        if (this.callbackSeries == null) {
            this.callbackSeries = new ArrayList<>();
        }
        return this.callbackSeries;
    }

    public void addCallbackSeries(String series) {

        this.getCallbackSeries().add(series);
    }

    /**
     * 获取 completeCommands 中不存在于 callbackSeries 中的键值
     *
     * @return 剩余的键集合
     */
    public Set<String> getRemainingKeys() {
        // 将 completeCommands 的键转换为 Set
        Set<String> commandKeys = new HashSet<>(commands.keySet());

        // 移除 callbackSeries 中存在的键
        commandKeys.removeAll(this.getCallbackSeries());

        return commandKeys;
    }

}
